package com.wang;

import org.quartz.*;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.SimpleTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 基于网络的Quartz DEMO，原文链接：http://blog.51cto.com/lavasoft/181907
 * 注意：Trigger设置的结束时间不足 || scheduler.shutdown()均会停止任务执行
 * 释放线程必须手动调用shceduler.shutdown();
 * @Author wlyfree
 * @Date 16:12
 */
public class MyJob implements Job {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String str = "do sth...." + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        logger.info("测试" + str);
    }

    public static void main(String[] args) {
        //JobDetail
        JobDetailImpl jobDetail = new JobDetailImpl();
        jobDetail.setJobClass(MyJob.class);
        jobDetail.setName("myJob1");
        jobDetail.setGroup("myJobGroup1");
        //Trigger
        SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
        simpleTrigger.setName("myTrigger1");
        simpleTrigger.setGroup("myTriggerGroup1");
        simpleTrigger.setStartTime(new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis() +  15100L);//结束时间
        simpleTrigger.setEndTime(calendar.getTime());
        simpleTrigger.setFireInstanceId("Trigger_001");
        simpleTrigger.setRepeatInterval(2000L);//重复间隔
        simpleTrigger.setRepeatCount(3);//重复次数
        //Scheduler
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler scheduler = null;
        try {
            scheduler = sf.getScheduler();
            scheduler.scheduleJob(jobDetail,simpleTrigger);
            scheduler.start();//开始调度
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(10500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //必须手动关闭，线程才会被释放掉
        try {
            scheduler.shutdown(true);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }
}
